package com.litchi.tutor.common.config.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.litchi.tutor.common.entity.User;
import com.litchi.tutor.common.util.JwtUtil;
import com.litchi.tutor.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author XuRuiPeng
 * @date 2021/11/1 10:07
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    UserMapper userMapper;

    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
    /**
     * 进入controller层之前拦截请求
     *
     * @param httpServletRequest
     * @param
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o) throws Exception {
        String token = httpServletRequest.getHeader("Authorization");
        if (token == null) {
            throw new RuntimeException("未携带token");
        }
        Integer id = JwtUtil.getId(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", id));
        if (user == null) {
            throw new RuntimeException("用户不存在，请重新登录");
        }

        // 判断权限
        if (!user.getStaff()) {
            throw new RuntimeException("用户权限不够");
        }

        // 验证token
        boolean verify = JwtUtil.verify(token);
        if (verify) {
            return true;
        }
        return false;
    }
    //访问controller之后 访问视图之前被调用
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
//        log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }
    //访问视图之后被调用
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
//        log.info("---------------视图渲染之后的操作-------------------------0");
    }
}
